package com.shen.core.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author: shenyang
 * @CreateTime: 2022-09-30  17:37
 * @Description: TODO
 * @Version: 1.0
 */
@RestControllerAdvice
public class CommonResults implements ResponseBodyAdvice<Object> {

    private static final Logger logger = LoggerFactory.getLogger(CommonResults.class);

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (returnType.getContainingClass().isAnnotationPresent(IgnoreResultAdvice.class)) {
            return false;
        }
        return !Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(IgnoreResultAdvice.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultData) {
            return body;
        }
        if (!(body instanceof String)) {
            return ResultFactory.success(body);
        }
        try {
            return objectMapper.writeValueAsString(ResultFactory.success(body));
        } catch (JsonProcessingException e) {
            logger.error("CommonResults=返回时json转换异常=", e);
            return ResultFactory.failure("CommonResults=返回时json转换异常");
        }
    }


}
